package com.example.fence.entity;

import com.example.fence.mqtt.MqttCallBackHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import com.example.fence.config.CommonConnectionConfig;

/**
 * 消息订阅客户端
 * @author yanglingcong*/
@Component
@Slf4j
public class MyMqttSubClient {

    private final MqttCallBackHandler MqttCallBackHandler;

    //todo 可能存在由于改变顺序之后导致的循环依赖问题！
    @Autowired
    @Lazy
    public MyMqttSubClient(MqttCallBackHandler MqttCallBackHandler) throws MqttException {
        this.MqttCallBackHandler = MqttCallBackHandler;
        subscribe();
    }

    public void subscribe()  {
        MqttAsyncClient client=null;

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        //断开之后自动重联
        connectOptions.setAutomaticReconnect(true);
        //设置会话心跳时间 代理和客户端在不发送消息的情况下可以忍受的最长时间
        connectOptions.setKeepAliveInterval(CommonConnectionConfig.KEEP_ALIVE);
        //不建立持久会话
        connectOptions.setCleanSession(true);
        //用户名
        connectOptions.setUserName(CommonConnectionConfig.USER_NAME);
        //密码
        connectOptions.setPassword(String.valueOf(CommonConnectionConfig.PASSWORD).toCharArray());
        //ID
        String clientid = MqttClient.generateClientId();

        try {
            client= new MqttAsyncClient(CommonConnectionConfig.HOST, clientid, new MemoryPersistence());
            //异步MQTT增加TOKEN
            IMqttToken token = client.connect(connectOptions);
            token.waitForCompletion();
            //消息回调
            client.setCallback( MqttCallBackHandler);

            client.subscribe(CommonConnectionConfig.TOPIC_B1, CommonConnectionConfig.QOS_1);

        }catch (MqttException e) {
            log.error("MQTT消息订阅异常 ");
            e.printStackTrace();
        }

    }
}
